home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part1 / 1394 < prev    next >
Encoding:
Text File  |  1996-08-05  |  2.1 KB  |  61 lines

  1. Path: mail2news.demon.co.uk!genesis.demon.co.uk
  2. From: Lawrence Kirby <fred@genesis.demon.co.uk>
  3. Newsgroups: comp.lang.c
  4. Subject: Re: Strcat Doesn't work for this?
  5. Date: Sat, 13 Jan 96 13:54:10 GMT
  6. Organization: none
  7. Message-ID: <821541250snz@genesis.demon.co.uk>
  8. References: <Pine.SOL.3.91.960111151925.25068C-100000@lore.cs.purdue.edu>
  9. Reply-To: fred@genesis.demon.co.uk
  10. X-NNTP-Posting-Host: genesis.demon.co.uk
  11. X-Newsreader: Demon Internet Simple News v1.27
  12. X-Mail2News-Path: genesis.demon.co.uk
  13.  
  14. In article <Pine.SOL.3.91.960111151925.25068C-100000@lore.cs.purdue.edu>
  15.            cookca@cs.purdue.edu "** Craig Cook **" writes:
  16.  
  17. >Here is my excerpt of code in question:
  18. >
  19. >
  20. >Putword(int w, char *imageChar)
  21. >{
  22. >        w = (w & 0xff);
  23. >        strcat( imageChar, (const char *)w );
  24. >
  25. >}
  26. >
  27. >Why does it core dump?  It should work right?
  28.  
  29. You seem to have some misconceptions about what casts do. A cast takes the
  30. *value* of its operand and tries to convert that value to the type specified
  31. in the cast. So (double)45 will take the integer value 45 and convert it
  32. to a double with the value 45 (or as close as possible). The C language
  33. doesn't explicitly define what happens when you cast an int to a pointer (
  34. except a constant expression with value 0 which is converted to a null
  35. pointer) - that is up to your implementation. Many implementation allow
  36. you create pointers to explicit memory locations using such a cast (e.g.
  37. (char *)45 creates a pointer value that points to a char at memory location
  38. 45), however you can't use this in portable C code. Maybe you were looking
  39. for something like the following:
  40.  
  41. void Putword(int w, char *imageChar)
  42. {
  43.         char *ptr = imageChar + strlen(imageChar);
  44.  
  45.         *ptr++ = w & 0xff;
  46.         *ptr = '\0';
  47. }
  48.  
  49. This actually results in undefined behaviour where char is equivalent to
  50. signed char and can't represent that value (w & 0xff). unsigned char
  51. may be a better choice in this code.
  52.  
  53. Usually if you find yourself resorting to pointer casts you are taking
  54. the wrong approach.
  55.  
  56. -- 
  57. -----------------------------------------
  58. Lawrence Kirby | fred@genesis.demon.co.uk
  59. Wilts, England | 70734.126@compuserve.com
  60. -----------------------------------------
  61.